package com.tang.portal.facade.admin.sys;

import com.tang.common.component.RedisCache;
import com.tang.common.constant.message.LocaleMessage;
import com.tang.framework.component.TokenService;
import com.tang.framework.core.domain.HttpResult;
import com.tang.framework.core.facade.Facade;
import com.tang.framework.core.model.LoginUser;
import com.tang.common.exception.BusinessException;
import com.tang.service.admin.model.req.ReqLogin;
import lombok.SneakyThrows;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

/**
 * @Author tang jun liang
 * @Date 2023/5/6 22:57
 */
@Service
public class SysOpenFacade extends Facade {

    @Resource
    private AuthenticationConfiguration authenticationConfiguration;

    @Resource
    private RedisCache redisCache;

    @Resource
    private TokenService tokenService;


    @SneakyThrows
    public HttpResult<LoginUser> login(ReqLogin login) {
//        String code = redisCache.get(login.getCodeToken());
//        if (!login.getCode().equals(code)) {
//            return HttpResult.error(messageSource.getMessage(LocaleMessage.Account.CODE_ERROR, null, request.getLocale()));
//        }
        AuthenticationManager authenticationManager = authenticationConfiguration.getAuthenticationManager();
        Authentication authenticate;
        try {
            authenticate = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword()));

        } catch (Exception e) {
            e.printStackTrace();
            if (e.getCause() instanceof BusinessException) {
                return HttpResult.error(((BusinessException) e.getCause()).getErrorCodeMessage());
            }
            if (e instanceof BadCredentialsException) {
                return HttpResult.error(messageSource.getMessage(LocaleMessage.Account.PASSWORD_ERROR, null, request.getLocale()));
            }
            if (e instanceof LockedException) {
                return HttpResult.error(messageSource.getMessage(LocaleMessage.Account.USER_LOCK, null, request.getLocale()));
            }
            return HttpResult.error(messageSource.getMessage(LocaleMessage.Account.LOGIN_ERROR, null, request.getLocale()));
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        loginUser.setLoginPassword(login.getPassword());
        return HttpResult.ok(tokenService.createToken(loginUser));
    }


}
